package com.lsh.oms.provider.common.rest;

import com.alibaba.dubbo.rpc.RpcException;
import com.lsh.base.common.model.CommonResult;
import org.apache.log4j.Logger;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

/**
 * Created by huangdong on 16/7/15.
 */
public class OmsRpcExceptionMapper implements ExceptionMapper<RpcException> {

    private static final Logger logger = Logger.getLogger(OmsRpcExceptionMapper.class);

    @Override
    public Response toResponse(RpcException e) {
        return this.handleConstraintViolationException((ConstraintViolationException) e.getCause());
    }

    protected Response handleConstraintViolationException(ConstraintViolationException e) {
        //获取bean validation错误信息
        StringBuilder message = new StringBuilder();
        for (ConstraintViolation cv : e.getConstraintViolations()) {
            message.append("\"").append(cv.getPropertyPath().toString()).append("\" ").append(cv.getMessage()).append("\n");
        }
        message.deleteCharAt(message.length() - 1);
        return Response.status(Response.Status.OK).entity(new CommonResult("E001", message.toString())).build();
    }
}
